clear
insheet using "nhgis0016_ds10_1850_county.csv"

gen countyfip = statea*10000 + (countya)

gen pop1850 = adq001
gen urbanover2500pop = adz001
gen popcities25000pop = ad9001
gen whitepop = ae6001
gen nonwhitefreepop = ae6002
gen nonwhiteslavepop = ae6003

egen totpop1850 = total(pop1850)
su totpop1850
save "ctypop.dta", replace

clear
use "EGLP_1850.dta"
gen countyfip = nhgisst*10000+(nhgiscty)

merge m:1 countyfip using "ctypop.dta"
rename _merge merge1850crosswalk

gen cty_fips = nhgisst_1990*100 + (nhgiscty_1990/10)


gen VAcounties = cty_fips==51177|cty_fips==51165|cty_fips==51121|cty_fips==51053

*For the VA counties replace the county fips of the surrounding county as the county of the independent city
*This will keep those records when merge to Normal Asylum counties

replace cty_fips = 51730 if cty_fips==51053
replace cty_fips = 51750 if cty_fips==51121
replace cty_fips = 51630 if cty_fips==51177
replace cty_fips = 51660 if cty_fips==51165

*Drop non-merged from crosswalk
drop if merge1850crosswalk==2 & VAcounties~=1

drop if merge1850crosswalk==1


rename cty_fips cty_fips1850

tostring cty_fips1850, gen(cty_fipstr)
gen statefip1850 = substr(cty_fipstr, 1,1) if length(cty_fipstr)==4
replace statefip1850 = substr(cty_fipstr, 1, 2) if length(cty_fipstr)==5
destring statefip1850, replace

tab icpsrst if statefip1850==.


#delimit cr
*Drop states that were not yet states on Census Day 1850: 

#delimit ;
drop if statefip1850==6|statefip1850==27|statefip1850==38|statefip1850==46|statefip1850==49|statefip==4|
statefip==8|statefip==16|statefip==30|statefip==31|statefip==32|statefip==35|statefip==40|
statefip==41|statefip==53|statefip==54|statefip==56;

#delimit cr

*Multiply variables of interest by weight

local vars pop1850 urbanover2500pop popcities25000pop whitepop nonwhitefreepop nonwhiteslavepop
foreach x of local vars{
gen `x'wt = `x'*weight
drop `x'
rename `x'wt `x'
}

*Collapse by cty_fips based on sums

collapse (sum) pop1850 urbanover2500pop popcities25000pop whitepop nonwhitefreepop nonwhiteslavepop, by(cty_fips1850)

save "ctypop1850_1990.dta", replace
